import React from 'react';
import { Form, Card, Button, Tag, Popover, Tooltip } from 'antd';
import { history } from 'umi'
import { get as getPath } from 'object-path';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import authHelper from '@/utils/auth/helper';
import { eventTrack } from '@/utils/track';
import Employee from '@/pages/Organization/OrgFlow/components/employee';
import { guid } from '@/utils/utils';
import { defaultFormatResult, useRequest } from '@/hooks';
import AuthComponent from '@/utils/auth/AuthComponent';
import { size } from 'lodash';
import { isSupervisorApprovaling } from '@/pages/Organization/OrgFlow/utils';
import { getDepartmentDetail } from '../services';
import { AUDIT } from '../constant';
import styles from './index.less';

const { checkCode } = authHelper;

// const modText = text => {
//     if (text) {
//         return `(${text})`;
//     }
//     return '';
// };
const auditStatusDict = {
    1: '审批中',
    2: '审批通过'
};
const modEmployeeName = text => {
    if (text.length > 6) {
        return `${text.substring(0, 5)}...`;
    }
    return text;
};
const DepartmentDetail = ({ location }) => {
    const { query } = location;

    const { data: info = {}, loading } = useRequest(() => getDepartmentDetail(query && query.organizationCode), {
        ...defaultFormatResult
    });

    const renderManage = React.useMemo(() => {
        if (info?.orgLeaders) {
            const {
                orgLeaders,
                organizationCode,
                auditStatus,
                // titleName: orgTitleName,
                organizationPermissions,
                leaderDutyAuditStatus
            } = info;
            if (orgLeaders.length > 0) {
                return orgLeaders.map(employee => {
                    const {
                        employeeName,
                        //  titleName,
                        showStatus,
                        dutyType
                    } = employee;
                    const keyId = guid();
                    const hasSupervisorEdit =
                        showStatus < 0 ||
                        auditStatus === 1 ||
                        organizationPermissions === 0 ||
                        dutyType === 1 ||
                        leaderDutyAuditStatus === 1;
                    return (
                        <React.Fragment key={keyId}>
                            <Popover
                                key={keyId}
                                getPopupContainer={node => node}
                                content={
                                    <Employee
                                        employeeCode={employee.employeeCode}
                                        organizationCode={employee.organizationCode}
                                        organizationType={info?.organizationType}
                                    />
                                }
                                placement="bottomLeft"
                            >
                                <span style={{ marginRight: 4 }}>
                                    {modEmployeeName(employeeName)}
                                    {/* {modText(titleName)} */}
                                    {dutyType === 0 ? (
                                        <Tag color="blue" style={{ marginLeft: 8 }}>
                                            兼
                                        </Tag>
                                    ) : null}
                                </span>
                            </Popover>
                            {hasSupervisorEdit ? null : (
                                <AuthComponent code="office:orgs:organization:detail:editLeader">
                                    <a
                                        className="setText"
                                        onClick={() => {
                                            history.push({
                                                pathname:
                                                    '/office/personnelManagement/organization/orgflow/supervisorEdit',
                                                query: {
                                                    organizationCode,
                                                    entranceSign: 'org'
                                                }
                                            });
                                        }}
                                    >
                                        修改
                                    </a>
                                </AuthComponent>
                            )}
                            {employee.showStatus === -1001 ? (
                                <Tooltip placement="top" title="主管设置审批中">
                                    <Tag
                                        style={{ cursor: 'pointer' }}
                                        color="orange"
                                        onClick={() => {
                                            history.push({
                                                pathname: '/personal/portal/myAuditRead/myAuditReadDetail',
                                                query: {
                                                    applicationNo: employee?.leaderApplicationNo
                                                }
                                            });
                                        }}
                                    >
                                        审批中
                                    </Tag>
                                </Tooltip>
                            ) : null}
                            {employee.showStatus === -1002 ? (
                                <Tooltip placement="top" title="主管修改审批中">
                                    <Tag
                                        style={{ cursor: 'pointer' }}
                                        color="orange"
                                        onClick={() => {
                                            history.push({
                                                pathname: '/personal/portal/myAuditRead/myAuditReadDetail',
                                                query: {
                                                    applicationNo: employee?.leaderApplicationNo
                                                }
                                            });
                                        }}
                                    >
                                        审批中
                                    </Tag>
                                </Tooltip>
                            ) : null}
                            {employee.showStatus === -1003 ? (
                                <Tooltip placement="top" title="主管卸任审批中">
                                    <Tag
                                        style={{ cursor: 'pointer' }}
                                        color="orange"
                                        onClick={() => {
                                            history.push({
                                                pathname: '/personal/portal/myAuditRead/myAuditReadDetail',
                                                query: {
                                                    applicationNo: employee?.leaderApplicationNo
                                                }
                                            });
                                        }}
                                    >
                                        审批中
                                    </Tag>
                                </Tooltip>
                            ) : null}
                        </React.Fragment>
                    );
                });
            }
            if (orgLeaders.length === 0 && info?.organizationType === 3) {
                return (
                    <>
                        {/* <span style={{ marginRight: 4 }}>-{modText(orgTitleName)}</span> */}
                        {auditStatus !== 1 && info?.organizationPermissions === 1 && (
                            <AuthComponent code="office:orgs:organization:detail:setLeader">
                                <a
                                    className="setText"
                                    onClick={() => {
                                        history.push({
                                            pathname: '/office/personnelManagement/organization/orgflow/supervisorSet',
                                            query: {
                                                organizationCode,
                                                entranceSign: 'org'
                                            }
                                        });
                                    }}
                                >
                                    设置
                                </a>
                            </AuthComponent>
                        )}
                    </>
                );
            }
            return '-';
        }
        return '-';
    }, [info]);

    const renderManageNull = React.useMemo(() => {
        // 部门审批中、岗位审批中、岗位缺失的情况不能设置修改
        if (
            info?.auditStatus === 1 ||
            info?.leaderDutyAuditStatus === 1 ||
            info?.leaderDutyAlias === ''
            // info?.organizationPermissions === 0
        ) {
            return '-';
        }
        return (
            <>
                -
                {info?.organizationPermissions === 1 ? (
                    <AuthComponent code="office:orgs:organization:detail:editLeader">
                        <a
                            style={{ marginLeft: 8 }}
                            onClick={() => {
                                history.push({
                                    pathname: '/office/personnelManagement/organization/orgflow/supervisorEdit',
                                    query: {
                                        organizationCode: info?.organizationCode,
                                        entranceSign: 'org'
                                    }
                                });
                            }}
                        >
                            设置
                        </a>
                    </AuthComponent>
                ) : null}
            </>
        );
    }, [info]);
    // organizationPermissions 数据权限控制
    const renderLeaderDutyAlias = React.useMemo(() => {
        if (info?.auditStatus === 1) {
            return info?.leaderDutyAlias || '-';
        }
        if (info?.leaderDutyAlias) {
            return (
                <>
                    <a
                        onClick={() => {
                            history.push({
                                pathname: '/office/personnelManagement/organization/postdetail',
                                state: {
                                    tabRoute: true,
                                    tabRefresh: true
                                },
                                query: {
                                    dutyCode: info?.leaderDutyCode,
                                    organizationCode: info?.organizationCode,
                                    organizationPermissions: info.organizationPermissions
                                }
                            });
                        }}
                    >
                        {info?.leaderDutyAlias}
                    </a>
                    {info?.leaderDutyAuditStatus === 1 ? (
                        <Tag color="orange" style={{ marginLeft: 8 }}>
                            审批中
                        </Tag>
                    ) : null}
                </>
            );
        }
        return (
            <>
                -
                {info?.organizationPermissions === 1 ? (
                    <AuthComponent code="office:orgs:organization:detail:addLeaderDuty">
                        <a
                            style={{ marginLeft: 8 }}
                            onClick={() => {
                                history.push({
                                    pathname: '/office/personnelManagement/organization/postadd',
                                    query: {
                                        organizationCode: info?.organizationCode,
                                        organizationPath: info?.organizationPath,
                                        organizationName: info?.organizationName
                                    }
                                });
                            }}
                        >
                            新增主管岗位
                        </a>
                    </AuthComponent>
                ) : null}
            </>
        );
    }, [info]);

    const baseInfo1 = [
        {
            key: '上级机构',
            value: (
                <div>
                    {getPath(info, 'parentOrganizationName', '')}
                    {info?.auditStatus ? (
                        <Tag color={info.auditStatus === 1 ? 'orange' : 'green'} style={{ marginLeft: 8 }}>
                            {auditStatusDict[info.auditStatus]}
                        </Tag>
                    ) : null}
                </div>
            )
        },
        {
            key: '部门名称(中文)',
            value: getPath(info, 'organizationName', '')
        },
        {
            key: '部门名称(英文)',
            value: getPath(info, 'organizationNameEnglish', '')
        },
        {
            key: '排序号',
            value: getPath(info, 'sort', '')
        }
    ];

    const baseInfo2 = [
        {
            key: '是否助理团',
            value: getPath(info, 'assistantFlag', '') === 1 ? '是' : '否'
        },
        {
            key: '关联机构',
            value: getPath(info, 'relativeOrganizations', [])
                .map(item => item.organizationName)
                .join('、')
        }
    ];

    const baseInfo3 = [
        {
            key: '部门电话',
            value: getPath(info, 'phone', '')
        },
        {
            key: '部门简介(中文)',
            value: getPath(info, 'organizationDesc', '')
        },
        {
            key: '部门简介(英文)',
            value: getPath(info, 'organizationDescEnglish', '')
        }
    ];
    const baseInfo4 = [
        {
            key: '主管岗位',
            value: renderLeaderDutyAlias
        },
        {
            key: '主管员工',
            value: size(info?.orgLeaders) > 0 ? renderManage : renderManageNull
        },
        {
            key: '部门(直属/下属)',
            value: (
                <>
                    <a
                        onClick={async () => {
                            history.push({
                                pathname: '/office/personnelManagement/organization/departmentManage',
                                query: {
                                    organizationPermissions: info?.organizationPermissions,
                                    organizationPath: info?.organizationPath,
                                    organizationType: 3,
                                    organizationCode: info?.organizationCode,
                                    organizationName: info?.organizationName,
                                    auditStatus: info?.auditStatus,
                                    num: info?.directDepartmentNum
                                }
                            });
                        }}
                    >
                        {info?.directDepartmentNum}
                    </a>{' '}
                    /{' '}
                    <a
                        onClick={async () => {
                            history.push({
                                pathname: '/office/personnelManagement/organization/subordinateManage',
                                query: {
                                    organizationPermissions: info?.organizationPermissions,
                                    organizationPath: info?.organizationPath,
                                    organizationCode: info?.organizationCode,
                                    organizationName: info?.organizationName,
                                    auditStatus: info?.auditStatus,
                                    organizationType: 3,
                                    num: info?.underDepartmentNumber
                                }
                            });
                        }}
                    >
                        {info?.underDepartmentNumber}
                    </a>
                </>
            )
        },
        {
            key: '直属岗位',
            value: (
                <a
                    onClick={async () => {
                        history.push({
                            pathname: '/office/personnelManagement/organization/postList',
                            query: {
                                organizationPermissions: info?.organizationPermissions,
                                organizationPath: info?.organizationPath,
                                organizationCode: info?.organizationCode,
                                organizationName: info?.organizationName,
                                auditStatus: info?.auditStatus,
                                num: info?.planNum
                            }
                        });
                    }}
                >
                    {info?.planNum}
                </a>
            )
        },
        {
            key: '直属员工',
            value: (
                <a
                    onClick={async () => {
                        history.push({
                            pathname: '/office/personnelManagement/organization/employeeList',
                            query: {
                                organizationCodes: info?.organizationCode || ''
                            }
                        });
                    }}
                >
                    {info?.employeeNum}
                </a>
            )
        }
    ];

    let baseInfoList = [...baseInfo1];

    if (info?.organizationType === 3) {
        baseInfoList = [...baseInfoList, ...baseInfo2];
    }

    baseInfoList = [...baseInfoList, ...baseInfo3];

    const renderBlock = arr =>
        arr.map(item => (
            <Form.Item label={item.key} key={item.key} style={{ margin: 0 }}>
                <div style={{ wordBreak: 'break-all' }}>{item.value}</div>
            </Form.Item>
        ));

    return (
        <PageHeaderWrapper>
            <Card
                title={
                    <>
                        部门信息
                        {getPath(info, 'auditStatus', '') !== '' && getPath(info, 'auditStatus', '') !== 2 && (
                            <Tag color="orange" style={{ marginLeft: 10 }}>
                                {AUDIT[getPath(info, 'auditStatus', '')]}
                            </Tag>
                        )}
                    </>
                }
                bordered={false}
                loading={loading}
                extra={
                    getPath(info, 'organizationPermissions', '') === 1 &&
                    checkCode('office:orgs:organization:edit') && (
                        <Button
                            type="primary"
                            disabled={
                                (getPath(info, 'auditStatus') !== undefined &&
                                    getPath(info, 'auditStatus', '') !== 2) ||
                                isSupervisorApprovaling(info)
                            }
                            onClick={async () => {
                                await eventTrack({
                                    eventName: 'personnel_management_organization_department_manage_info_edit_click',
                                    pageName: 'personnel_management_organization',
                                    eventProps: {
                                        click_context: `${query.organizationName}-编辑`
                                    }
                                });
                                history.push({
                                    pathname: '/office/personnelManagement/organization/departmentedit',
                                    query: {
                                        organizationCode: query && query.organizationCode,
                                        organizationPath: query && query.organizationPath,
                                        organizationName: query && query.organizationName
                                    }
                                });
                            }}
                        >
                            编辑
                        </Button>
                    )
                }
            >
                <div className={styles.title}>基本信息</div>
                <Form className={styles.formWrap}>{renderBlock(baseInfoList)}</Form>
                <br />
                <div className={styles.title}>管理情况</div>
                <Form className={styles.formWrap}>{renderBlock(baseInfo4)}</Form>
            </Card>
        </PageHeaderWrapper>
    );
};

export default DepartmentDetail;
